import 'package:flutter/material.dart';
// ignore: import_of_legacy_library_into_null_safe
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import '../../services/ScreenAdaper.dart';
import 'package:dio/dio.dart';
import '../../model/FocusModel.dart';
import '../../model/Data02.dart';

import '../../config/Config.dart';

class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with AutomaticKeepAliveClientMixin {
  List _focusData = [];
  List<dynamic> _data02 = [];
  @override
  bool get wantKeepAlive => true; // 缓存页面重要代码
  @override
  void initState() {
    super.initState();
    print('刷新了HOME页面');
    _getFocusData();
    _getData02();
  }

  /// 轮播图组件数据
  _getFocusData() async {
    // print('111111FR');
    String api = '${Config.domain}index?status=1';
    var result = await Dio().get(api);
    // print('55555555555');
    // print(result);
    var focusList = FocusModel.fromJson(result.data);
    setState(() {
      this._focusData = focusList.product;
    });
  }

  /// 轮播图组件
  Widget _swiperWidget01() {
    if (this._focusData.length > 0) {
      return Container(
        child: AspectRatio(
          aspectRatio: 2 / 1, // 宽高比
          child: Swiper(
            key: UniqueKey(), // 这个必须添加，代表唯一
            itemBuilder: (BuildContext context, int index) {
              String pic = this._focusData[index].indexImg;
              return new Image.network(
                Config.domain + pic.replaceAll('\\', '/'),
                fit: BoxFit.fill,
              );
            },
            itemCount: this._focusData.length,
            pagination: new SwiperPagination(),
            control: new SwiperControl(),
            autoplay: true,
          ),
        ),
      );
    } else {
      return Text('加载中。。。');
    }
  }

  /// 轮播图组件
  Widget _swiperWidget() {
    List<Map> imgList = [
      {
        'url':
            'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fnimg.ws.126.net%2F%3Furl%3Dhttp%253A%252F%252Fdingyue.ws.126.net%252F2021%252F0521%252F797a4747j00qtgemj000dd200ci008cg00ci008c.jpg%26thumbnail%3D650x2147483647%26quality%3D80%26type%3Djpg&refer=http%3A%2F%2Fnimg.ws.126.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1634050644&t=a99356900a4f642b5fc86e8fe7519a12'
      },
      {
        'url':
            'https://ss1.baidu.com/-4o3dSag_xI4khGko9WTAnF6hhy/zhidao/wh%3D450%2C600/sign=e60aae2dbf12c8fcb4a6fec9c933be73/55e736d12f2eb9380fd1a6ffd3628535e5dd6f7b.jpg'
      },
      {
        'url':
            'https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fdingyue.ws.126.net%2F2020%2F0521%2F50e959cej00qaod64000cc000ci008cc.jpg&refer=http%3A%2F%2Fdingyue.ws.126.net&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=jpeg?sec=1634050748&t=60a7da7c71c828d5969e5ab4a47af02c'
      }
    ];
    return Container(
      child: AspectRatio(
        aspectRatio: 1.5 / 1, // 宽高比450/300
        child: Swiper(
          key: UniqueKey(), // 这个必须添加，代表唯一
          itemBuilder: (BuildContext context, int index) {
            return new Image.network(
              imgList[index]['url'],
              fit: BoxFit.fill,
            );
          },
          itemCount: imgList.length,
          pagination: new SwiperPagination(),
          control: new SwiperControl(),
          autoplay: true,
        ),
      ),
    );
  }

  /// 标题组件
  Widget _titleWidget(value) {
    return Container(
      height: 20.h,
      margin: EdgeInsets.only(left: 10.w, top: 5.w, bottom: 5.w),
      padding: EdgeInsets.only(left: 10.w),
      decoration: BoxDecoration(
          border: Border(left: BorderSide(color: Colors.red, width: 6.w))),
      child: Text(value, style: TextStyle(color: Colors.pink)),
    );
  }

  /// 横向列表ListView
  Widget _hotProductListWidget() {
    int myCount = 5;
    // ListView里想要包裹ListView就要套进Container
    return Container(
      height: 124.w,
      padding: EdgeInsets.all(10.w),
      child: ListView.builder(
        scrollDirection: Axis.horizontal, // 这个控制纵向还是横向滚动
        itemBuilder: (context, index) {
          return Column(
            children: <Widget>[
              Container(
                height: 80.w,
                width: 80.w,
                margin: EdgeInsets.only(
                    right: (index + 1) == myCount
                        ? 0
                        : 15.w), // 设置最后一个右边距为0，啊我太机智了呢，用的是JS的写法蒙的
                child: Image.network(
                  'https://img2.baidu.com/it/u=2205513205,3397208780&fm=15&fmt=auto&gp=0.jpg',
                  fit: BoxFit.cover,
                ),
              ),
              Container(
                padding: EdgeInsets.only(top: 10.h),
                height: 24.w,
                child: Text('第$index条'),
              )
            ],
          );
        },
        itemCount: myCount,
      ),
    );
  }

  /// 纵向列表组件
  Widget _recProductItemWidget() {
    // 设置单个项目的宽度-用设备宽度减去30除以2，因为是2列
    double itemWidth = (ScreenAdaper.getScreenWidth() - 30.w) / 2;

    return Container(
      padding: EdgeInsets.all(10.w),
      width: itemWidth,
      decoration:
          BoxDecoration(border: Border.all(color: Colors.black, width: 1.w)),
      child: Column(
        children: <Widget>[
          Container(
            width: double.infinity,
            child: AspectRatio(
              aspectRatio: 1 / 1, // 防止服务器返回图片高度宽度不一致导致的页面问题
              child: Image.network(
                'https://img0.baidu.com/it/u=1326722126,2183368927&fm=15&fmt=auto&gp=0.jpg',
                fit: BoxFit.cover,
              ),
              key: UniqueKey(),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 20.h),
            child: Text(
              '清爽夏天的好看图片啦啦啦啦啦啦好看图片啦啦啦啦啦啦',
              maxLines: 2, // 超过2行就换行
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: Colors.pink),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: 6.w),
            child: Stack(
              children: <Widget>[
                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    '￥188.00',
                    style: TextStyle(color: Colors.red, fontSize: 16),
                  ),
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child: Text(
                    '￥198.00',
                    style: TextStyle(
                        color: Colors.black38,
                        fontSize: 16,
                        decoration: TextDecoration.lineThrough),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
  }

  // 获取下面的列表的数据
  _getData02() async {
    String api = '${Config.domain}kind/new?kid=1';
    var result = await Dio().get(api);
    // print('6666666666666');
    // print(result);
    var focusList = BottomObj.fromJson(result.data);
    setState(() {
      this._data02 = focusList.product;
      // print('7777777777');
      // print(this._data02[0].img);
    });
  }

  Widget _recProductItemWidget01() {
    // 设置单个项目的宽度-用设备宽度减去30除以2，因为是2列
    double itemWidth = (ScreenAdaper.getScreenWidth() - 30.w) / 2;
    return Container(
      // 把下面的那个拿上来只修改children
      padding: EdgeInsets.all(10.w),
      child: Wrap(
        runSpacing: 10, //上下距离
        spacing: 10, // 左右距离
        children: this._data02.map((value) {
          String pic = Config.domain + value.img;
          // 这一大堆代码是复制过来的
          // 代码不动，套进循环里
          return Container(
            padding: EdgeInsets.all(10.w),
            width: itemWidth,
            decoration: BoxDecoration(
                border: Border.all(color: Colors.black, width: 1.w)),
            child: Column(
              children: <Widget>[
                Container(
                  width: double.infinity,
                  child: AspectRatio(
                    aspectRatio: 1 / 1, // 防止服务器返回图片高度宽度不一致导致的页面问题
                    child: Image.network(
                      pic,
                      fit: BoxFit.cover,
                    ),
                    key: UniqueKey(),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(top: 20.h),
                  child: Text(
                    '清爽夏天的好看图片啦啦啦啦啦啦好看图片啦啦啦啦啦啦',
                    maxLines: 2, // 超过2行就换行
                    overflow: TextOverflow.ellipsis,
                    style: TextStyle(color: Colors.pink),
                  ),
                ),
                Padding(
                  padding: EdgeInsets.only(top: 6.w),
                  child: Stack(
                    children: <Widget>[
                      Align(
                        alignment: Alignment.centerLeft,
                        child: Text(
                          '￥188.00',
                          style: TextStyle(color: Colors.red, fontSize: 16),
                        ),
                      ),
                      Align(
                        alignment: Alignment.centerRight,
                        child: Text(
                          '￥198.00',
                          style: TextStyle(
                              color: Colors.black38,
                              fontSize: 16,
                              decoration: TextDecoration.lineThrough),
                        ),
                      )
                    ],
                  ),
                )
              ],
            ),
          );
        }).toList(),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // return Text(
    //   '我是Home组件'
    // );
    // 测试跳转功能
    // return Center(
    //   child: Column(
    //     mainAxisAlignment: MainAxisAlignment.center,
    //     children: <Widget>[
    //       ElevatedButton(
    //         onPressed: (){
    //           Navigator.pushNamed(context, '/search');
    //         }, child: Text('跳转到搜索页面'))
    //     ],
    //     ),
    // );
    // 测试跳转功能
    return ListView(
      children: <Widget>[
        _swiperWidget01(),
        _swiperWidget(),
        _titleWidget('横向组件啦'),
        _hotProductListWidget(),
        _titleWidget('纵向组件01'),
        _recProductItemWidget01(),
        // Text('猜你喜欢', style: TextStyle(color: Colors.pink))
        _titleWidget('纵向组件02'),
        Container(
          padding: EdgeInsets.all(10.w),
          child: Wrap(
            runSpacing: 10, //上下距离
            spacing: 10, // 左右距离
            children: <Widget>[
              _recProductItemWidget(),
              _recProductItemWidget(),
              _recProductItemWidget(),
              _recProductItemWidget(),
            ],
          ),
        )
      ],
    );
  }
}
